package com.example.BlockChain.controller;

import com.example.BlockChain.dto.ProductSummaryDTO;
import com.example.BlockChain.entity.*;
import com.example.BlockChain.service.ProductService;
import com.example.BlockChain.service.UserService;
import com.example.BlockChain.utils.DateUtils;
import com.example.BlockChain.utils.EthUtils;
import com.example.BlockChain.utils.MD5Utils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;
import java.util.Map;

import static com.example.BlockChain.utils.EthUtils.publicKeyToAddress;

@RestController
public class ProductController {
    @Resource
    private ProductService productService;

/**
 * 获取所有商品列表
 *
 * @return ResponseEntity 包装的JSON结果，包含店铺数据和请求状态
 */
    @GetMapping(value = "/getgoods")
    public ResponseEntity<JSONObject> getgoods(@RequestParam int userid) {
        // 创建返回的JSON对象
        JSONObject response = new JSONObject();
        try {
             //调用服务层方法获取店铺列
            response.setO(userid);
            List<TProduct> productList = productService.getAllGoods(userid);
           // response.setO(productList);
            if (productList.isEmpty()) {
                // 如果店铺列表为空，返回提示信息
                response.setCode("404");
                response.setMsg("暂无商品信息");
                return new ResponseEntity<>(response, HttpStatus.OK);
            }
            // 将店铺列表放入JSON对象
            response.setCode("200");
            response.setMsg("商品列表获取成功");
            response.setO(productList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            // 处理异常情况并返回错误信息
            response.setCode("500");
            response.setMsg("服务器内部错误: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取商品接口  通过商家id获取，用于显示商品列表
     * @param
     * @return
     */

    @RequestMapping("/getProduct")
    public ResponseEntity<JSONObject> getProductsByMerchantId(@RequestBody Map<String, Integer> request) {
        JSONObject jo = new JSONObject();
        // 校验商家 ID
        Integer merchantId = request.get("merchantId");
        if (merchantId == null || merchantId <= 0) {
            jo.setCode("-1");
            jo.setMsg("商家ID有误");
            return new ResponseEntity<>(jo, HttpStatus.BAD_REQUEST);
        }
        // 调用 Service 层获取商品信息
        List<ProductSummaryDTO> products = productService.getProductsByMerchantId(merchantId);
        if (products == null || products.isEmpty()) {
            jo.setCode("0");
            jo.setMsg("此商家暂无商品");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        jo.setCode("1");
        jo.setMsg("查询成功");
        jo.setO(products);
        return new ResponseEntity<>(jo, HttpStatus.OK);

    }

    /**
     * 新增商品接口
     *
     * @param product 商品信息
     * @return 新增结果
     */
    @RequestMapping("/addProduct")
    public ResponseEntity<JSONObject> addProduct(@RequestBody TProduct product) {
        JSONObject jo = new JSONObject();

        // 校验商品字段
        if (product.getProductName() == null || "".equals(product.getProductName())) {
            jo.setCode("-1");
            jo.setMsg("商品名称不能为空");
            System.out.println("商品增加请求: " + product);
            System.out.println("商品名: " + product.getProductName());
            System.out.println("价格: " + product.getPrice());
            System.out.println("库存: " + product.getStockQuantity());
            jo.setO(product);
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }
        if (product.getPrice() == null) {
            jo.setCode("-1");
            jo.setMsg("价格不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }
        if (product.getStockQuantity() <= 0) {
            jo.setCode("-1");
            jo.setMsg("库存数量必须大于0");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        productService.addProduct(product);

        jo.setCode("1");
        jo.setMsg("新增商品成功");
        return new ResponseEntity<>(jo, HttpStatus.OK);
    }

    /**
     * 编辑商品接口,编辑后更新到数据库中去
     *
     * @param product 商品信息
     * @return 编辑结果
     */
    @RequestMapping("/updateProduct")
    public ResponseEntity<JSONObject> updateProduct(@RequestBody TProduct product) {
        JSONObject jo = new JSONObject();
        jo.setO(product);
        System.out.println("Received product: " + product.getProductId());

        // 校验商品 ID
        if (product.getProductId() <= 0) {
            jo.setCode("-1");
            jo.setMsg("商品 ID 无效");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 校验商品名称
        if (product.getProductName() != null && product.getProductName().trim().isEmpty()) {
            jo.setCode("-1");
            jo.setMsg("商品名称不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 校验价格
        if (product.getPrice() != null && product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            jo.setCode("-1");
            jo.setMsg("价格不能小于或等于 0");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 校验库存
        if (product.getStockQuantity() <=0 && product.getStockQuantity() <= 0) {
            jo.setCode("-1");
            jo.setMsg("库存数量必须大于 0");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        // 调用 Service 层方法
        boolean success = productService.editProduct(product);
        if (success) {
            jo.setCode("1");
            jo.setMsg("编辑商品成功");
        } else {
            jo.setCode("-1");
            jo.setMsg("编辑商品失败，商品可能不存在");
        }

        return new ResponseEntity<>(jo, HttpStatus.OK);
    }

    /**
     * 删除商品接口
     *
     * @param product 包含商品ID的对象
     * @return 删除结果
     */
    @RequestMapping("/deleteProduct")
    public ResponseEntity<JSONObject> deleteProduct(@RequestBody TProduct product) {
        JSONObject jo = new JSONObject();

        // 校验商品ID
        if (product.getProductId() <= 0) {
            jo.setCode("-1");
            jo.setMsg("商品ID无效");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }

        productService.deleteProduct((long) product.getProductId());

        jo.setCode("1");
        jo.setMsg("删除商品成功");
        return new ResponseEntity<>(jo, HttpStatus.OK);
    }

    /**
     * 多选删除商品，勾选商品前面的复选框可以同时删除多个商品
     */
    //注：此方法在postman上进行post请求时候的格式如下  例如要删除商品Id为2，3的商品，json格式应为[2,3]
    @RequestMapping("/deleteMultiple")
    public ResponseEntity<JSONObject> deleteMultiple(@RequestBody List<Long> productIds) {
        JSONObject jo = new JSONObject();


        // 校验商品ID列表
        if (productIds == null || productIds.isEmpty()) {
            jo.setCode("-1");
            jo.setMsg("商品ID列表不能为空");
            return new ResponseEntity<>(jo, HttpStatus.OK);
        }
        try {
            // 批量删除商品
            productService.deleteProductsByIds(productIds);

            jo.setCode("-1");
            jo.setMsg( "成功删除" + productIds.size() + "个商品");
        } catch (Exception e) {
            jo.setCode("-1");
            jo.setMsg("删除商品失败: " + e.getMessage());
        }

        return new ResponseEntity<>(jo, HttpStatus.OK);
    }
}
